﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DMS.Base;
using DMS.BaseClass;
using DMS.Business.Modules.Organization;
using DMS.Business.Utility;
using DMS.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace DMS.Business.Modules.ArchivesManagement
{
    public class BaseInfoService
    {
        public static AM_BaseInfo GetBaseInfoById(string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                return db.AM_BaseInfo.Where(p => p.BaseInfoID == baseInfoId).FirstOrDefault();
            }
        }

        public static AM_BaseInfo GetBaseInfoByInsuranceCode(string insuranceCode)
        {
            using (var db = new DMSEntities())
            {
                return db.AM_BaseInfo.Where(p => p.InsuranceCode == insuranceCode).FirstOrDefault();
            }
        }

        /// <summary>
        /// 查询基本信息
        /// </summary>
        /// <param name="actor">参与者，如果为空则不过滤权限</param>
        /// <param name="condition">条件</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页条数，如果小于等于0，则返回所有</param>
        /// <param name="total">总数</param>
        /// <returns></returns>
        public static List<AM_BaseInfo> GetBaseInfos(User actor, string condition, int pageIndex, int pageSize,
                                                     out int total)
        {
            using (var db = new DMSEntities())
            {
                //权限过滤
                condition += GetLimitCondition(actor);

                int skinCount = (pageIndex - 1)*pageSize;

                var q = db.AM_BaseInfo
                    .Where("it.IsDeleted=false " + condition)
                    .OrderByDescending(p => p.BoxCode);

                total = q.Count();

                if (skinCount > total && pageSize > 0)
                {
                    skinCount = total - (total%pageSize);
                }

                List<AM_BaseInfo> list;
                if (pageSize > 0)
                    list = q.Skip(skinCount).Take(pageSize).ToList();
                else
                    list = q.ToList();

                return list;
            }
        }

        /// <summary>
        /// 获取权限过滤条件
        /// </summary>
        /// <returns></returns>
        private static string GetLimitCondition(User actor)
        {
            string condition = "";

            if (actor == null)
                return "";

            if (actor.IsInRole("系统管理员;县局管理员"))
                return "";

            ////配送管理员只能查自己管的单
            //if (actor.IsInRole("档案管理员;一般管理员"))
            //{
            //    string typeIDs = "";
            //    List<PS_ProjectTypes> list = new ProjectTypeService().GetTopTypesByAdminID(actor.ID);
            //    if (list != null && list.Count > 0)
            //    {
            //        foreach (PS_ProjectTypes obj in list)
            //            typeIDs += "'" + obj.ProjectTypeID + "',";
            //        if (!string.IsNullOrEmpty(typeIDs))
            //        {
            //            typeIDs = typeIDs.Substring(0, typeIDs.Length - 1);
            //        }

            //        condition += string.Format(" and it.ProjectTypeID in ({0}) ", typeIDs);
            //    }
            //}
            //    //部门配送管理员只能查自己管的大部门的单
            //else if (actor.IsInRole("部门配送管理员"))
            //{
            //    string memberScope = UserHelper.GetMemberScope(actor.ID, "部门配送管理员");

            //    string[] deptIds = memberScope.Split(';');
            //    string inString = "";
            //    foreach (string deptId in deptIds)
            //    {
            //        inString += "'" + deptId + "',";
            //    }
            //    if (!string.IsNullOrEmpty(inString))
            //    {
            //        inString = inString.Substring(0, inString.Length - 1);
            //    }

            //    condition += string.Format(" and it.ApplierBigDeptID in ({0}) ", inString);
            //}
            //    //配送商只能查自己公司并且该帐号所属项目类型的单
            //else if (actor is SupplierAccount)
            //{
            //    SupplierAccount account = actor as SupplierAccount;
            //    condition += string.Format(" and it.SupplierID='{0}' and it.ProjectTypeID='{1}' and it.Status!='SP' ",
            //                               account.SupplierID, account.ProjectTypeID);
            //}
            //    //普通用户只能查自己申请的单
            //else
            {
                condition += string.Format(" and it.DeptID='{0}'", actor.BigDept.ID);
            }

            return condition;

        }

        public static void SaveOrUpdateBaseInfo(AM_BaseInfo baseInfo)
        {
            using (var db = new DMSEntities())
            {
                var tBaseInfo = db.AM_BaseInfo.FirstOrDefault(p => p.BaseInfoID == baseInfo.BaseInfoID);
                if (tBaseInfo != null) //更新
                {
                    db.ApplyCurrentValues("AM_BaseInfo", baseInfo);
                }
                else //新增
                {
                    baseInfo.IsDeleted = false;
                    db.AM_BaseInfo.AddObject(baseInfo);
                }
                db.SaveChanges();
            }
        }

        public static void SaveBaseInfoList(List<AM_BaseInfo> baseInfoList)
        {
            using (var db = new DMSEntities())
            {
                foreach(var baseInfo in baseInfoList)
                {
                    db.AM_BaseInfo.AddObject(baseInfo);
                }
                db.SaveChanges();
            }
        }

        public static void DeleteBaseInfo(string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var baseInfo = db.AM_BaseInfo.Where(p => p.BaseInfoID == baseInfoId).FirstOrDefault();
                if (baseInfo != null)
                {
                    baseInfo.IsDeleted = true;
                    db.SaveChanges();
                }
            }
        }

        public static bool IsUnitNameExist(string unitName,string type,string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var count =
                    db.AM_BaseInfo.Where(p => p.UnitName == unitName && p.Type == type && p.BaseInfoID != baseInfoId).
                        Count();
                return count > 0;
            }
        }

        public static bool IsTaxCodeExist(string taxCode,string type,string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var count =
                    db.AM_BaseInfo.Where(p => p.TaxCode == taxCode && p.Type == type && p.BaseInfoID != baseInfoId).
                        Count();
                return count > 0;
            }
        }

        public static bool IsInsuranceCodeExist(string insuranceCode,string baseInfoId)
        {
            using (var db = new DMSEntities())
            {
                var count =
                    db.AM_BaseInfo.Where(p => p.InsuranceCode == insuranceCode && p.BaseInfoID != baseInfoId).
                        Count();
                return count > 0;
            }
        }

        public static List<DataTable> GetBaseInfoTable(User actor, string condition,string formType)
        {
            int total;
            var list = GetBaseInfos(actor, condition, 0, -1, out total);

            if (list.Count > 65535)
                return null;

            if (formType == "GR")
            {
                return GetGRExportRows(list, formType);
            }
            return GetExportRows(list, formType);
        }

        private static string GetTypeName(string formType)
        {
            string tableName = "";
            switch (formType)
            {
                case "DW":
                    tableName = "单位基本信息";
                    break;
                case "GTH":
                    tableName = "个体户基本信息";
                    break;
                case "GR":
                    tableName = "个人基本信息";
                    break;
            }
            return tableName;
        }

        private  static string GetInsuaranceTypeString(AM_BaseInfo baseInfo)
        {
            string typeString = "";
            if (bool.Parse(baseInfo.Yanglao.ToString()))
                typeString += "养老、";
            if (bool.Parse(baseInfo.Gongshang.ToString()))
                typeString += "工伤、";
            if (bool.Parse(baseInfo.Shiye.ToString()))
                typeString += "失业、";
            if (bool.Parse(baseInfo.Yiliao.ToString()))
                typeString += "医疗、";
            if (bool.Parse(baseInfo.Shengyu.ToString()))
                typeString += "生育、";
            if (!string.IsNullOrEmpty(typeString))
            {
                typeString = typeString.Substring(0, typeString.Length - 1);
            }
            return typeString;
        }

        private static List<DataTable> GetExportRows(List<AM_BaseInfo> list ,string formType)
        {
            List<DataTable> tables = new List<DataTable>();

            #region 表头初始化

            DataTable dt = new DataTable();
            dt.TableName = GetTypeName(formType);
            dt.Columns.Add("档案盒编号");
            dt.Columns.Add("档案盒所在位置");
            dt.Columns.Add("单位社保号");
            dt.Columns.Add("单位名称");
            dt.Columns.Add("纳税编码");
            dt.Columns.Add("缴费单位类型");
            dt.Columns.Add("联系人");
            dt.Columns.Add("联系电话手机");
            dt.Columns.Add("联系电话座机");
            dt.Columns.Add("社保登记日期");
            dt.Columns.Add("参保人数");
            dt.Columns.Add("参保险种");
            dt.Columns.Add("专管员");
            dt.Columns.Add("备注");

            DataRow dr1 = dt.NewRow();

            dr1["档案盒编号"] = "档案盒编号";
            dr1["档案盒所在位置"] = "档案盒所在位置";
            dr1["单位社保号"] = "单位社保号";
            dr1["单位名称"] = "单位名称";
            dr1["纳税编码"] = "纳税编码";
            dr1["缴费单位类型"] = "缴费单位类型";
            dr1["联系人"] = "联系人";
            dr1["联系电话手机"] = "联系电话(手机)";
            dr1["联系电话座机"] = "联系电话(座机)";
            dr1["社保登记日期"] = "社保登记日期";
            dr1["参保人数"] = "参保人数(人)";
            dr1["参保险种"] = "参保险种";
            dr1["专管员"] = "专管员";
            dr1["备注"] = "备注";
            dt.Rows.Add(dr1);

            #endregion

            foreach (var exportRow in list)
            {
                DataRow dr = dt.NewRow();
                dr["档案盒编号"] = exportRow.BoxCode;
                dr["档案盒所在位置"] = exportRow.BoxPosition;
                dr["单位社保号"] = exportRow.InsuranceCode;
                dr["单位名称"] = exportRow.UnitName;
                dr["纳税编码"] = exportRow.TaxCode;
                dr["缴费单位类型"] = exportRow.PayUnitType;
                dr["联系人"] = exportRow.Contact;
                dr["联系电话手机"] = exportRow.Mobile;
                dr["联系电话座机"] = exportRow.Phone;
                dr["社保登记日期"] = exportRow.RegistDate.HasValue ? exportRow.RegistDate.Value.ToShortDateString() : "";
                dr["参保人数"] = exportRow.InsuranceCount;
                dr["参保险种"] = GetInsuaranceTypeString(exportRow);
                dr["专管员"] = exportRow.Admin;
                dr["备注"] = exportRow.Remark;
                dt.Rows.Add(dr);
            }
            tables.Add(dt);
            return tables;
        }

        private static List<DataTable> GetGRExportRows(List<AM_BaseInfo> list ,string formType)
        {
            List<DataTable> tables = new List<DataTable>();

            #region 表头初始化

            DataTable dt = new DataTable();
            dt.TableName = GetTypeName(formType);
            dt.Columns.Add("档案盒编号");
            dt.Columns.Add("档案盒所在位置");
            dt.Columns.Add("个人社保号");
            dt.Columns.Add("缴费人姓名");
            dt.Columns.Add("身份证号码");
            dt.Columns.Add("纳税编码");
            dt.Columns.Add("缴费单位类型");
            dt.Columns.Add("联系电话");
            dt.Columns.Add("社保登记日期");
            dt.Columns.Add("参保险种");
            dt.Columns.Add("专管员");
            dt.Columns.Add("备注");

            DataRow dr1 = dt.NewRow();

            dr1["档案盒编号"] = "档案盒编号";
            dr1["档案盒所在位置"] = "档案盒所在位置";
            dr1["个人社保号"] = "个人社保号";
            dr1["缴费人姓名"] = "缴费人姓名";
            dr1["身份证号码"] = "身份证号码";
            dr1["纳税编码"] = "纳税编码";
            dr1["缴费单位类型"] = "缴费单位类型";
            dr1["联系电话"] = "联系电话";
            dr1["社保登记日期"] = "社保登记日期";
            dr1["参保险种"] = "参保险种";
            dr1["专管员"] = "专管员";
            dr1["备注"] = "备注";
            dt.Rows.Add(dr1);

            #endregion

            foreach (var exportRow in list)
            {
                DataRow dr = dt.NewRow();
                dr["档案盒编号"] = exportRow.BoxCode;
                dr["档案盒所在位置"] = exportRow.BoxPosition;
                dr["个人社保号"] = exportRow.InsuranceCode;
                dr["缴费人姓名"] = exportRow.PayerName;
                dr["身份证号码"] = exportRow.IdentityCardNo;
                dr["纳税编码"] = exportRow.TaxCode;
                dr["缴费单位类型"] = exportRow.PayUnitType;
                dr["联系电话"] = exportRow.Mobile;
                dr["社保登记日期"] = exportRow.RegistDate.HasValue?exportRow.RegistDate.Value.ToShortDateString():"";
                dr["参保险种"] = GetInsuaranceTypeString(exportRow);
                dr["专管员"] = exportRow.Admin;
                dr["备注"] = exportRow.Remark;
                dt.Rows.Add(dr);
            }
            tables.Add(dt);
            return tables;
        }
    }
}
